package com.question.service;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.achievement.dao.SubjectRepository;
import com.achievement.entity.Subject;
import com.common.util.TablePage;
import com.paper.dao.SubtopicsRepository;
import com.question.dao.ExplanationRepository;
import com.question.entity.Explanation;
import com.question.entity.Options;
import com.question.entity.dto.ExplanationDTO;

@Service
@Transactional
public class ExplService implements IExplService {
	@Autowired
	private ExplanationRepository explDao;
	@Autowired
	private SubjectRepository subjectDao;
	@Autowired
	private SubtopicsRepository subtopicsDao;

	public void saveOrUpdate(Explanation explanation, Long subjectId, String reference) {
		Subject subject = subjectDao.findOne(subjectId);
		explanation.setSubject(subject);
		
		Options options = new Options();
		options.setContent(reference);
		explanation.setReference(options);
		explDao.save(explanation);
	}

	public void delete(Long id) {
		Explanation explanation = explDao.findOne(id);
		explanation.setSubject(null);
		explDao.save(explanation);
		explDao.delete(id);
	}

	public TablePage<ExplanationDTO> findPage(Specification<Explanation> spec, Pageable pageable) {
		Page<Explanation> page = explDao.findAll(spec, pageable);
		List<ExplanationDTO> list = new ArrayList<ExplanationDTO>();
		for(Explanation e:page.getContent()) {
			list.add(new ExplanationDTO(e, e.getSubject().getName(), e.getReference().getContent()));
		}
		return TablePage.getTablePage(new PageImpl<ExplanationDTO>(list, pageable, page.getTotalElements()));
	}

	@Override
	public TablePage<Explanation> findRealPage(Specification<Explanation> spec, Pageable pageable) {
		// TODO Auto-generated method stub
		return TablePage.getTablePage(explDao.findAll(spec, pageable));
	}

	@Override
	public Explanation findOne(Long id) {
		// TODO Auto-generated method stub
		return explDao.findOne(id);
	}

	@Override
	public boolean isNumExist(Explanation explanation) {
		// TODO Auto-generated method stub
		Explanation s = explDao.findByNum(explanation.getNum());
		if(null!=s&&s.getId()!=explanation.getId())return true;
		return false;
	}

	@Override
	public boolean isUsing(Long id) {
		// TODO Auto-generated method stub
		if(subtopicsDao.findByExplId(id).size()>0)
			return true;
		return false;
	}
	
	
}
